package cn.laixueit.service.impl;

import cn.laixueit.common.Utils;
import cn.laixueit.mapper.CartMapper;
import cn.laixueit.mapper.OrderMapper;
import cn.laixueit.pojo.Cart;
import cn.laixueit.pojo.Order;
import cn.laixueit.pojo.OrderExample;
import cn.laixueit.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartMapper cartMapper;

    @Transactional(rollbackFor = RuntimeException.class)
    public void addOrder(List<Cart> carts, Integer uid) {
        Date date = new Date();
        for (Cart cart : carts) {
            Order order = new Order();
            order.setUid(uid);
            order.setPaytime(date);
            order.setId(Utils.hashId());
            order.setName(cart.getName());
            order.setCreatetime(date);
            order.setImg(cart.getImg());
            order.setStatus(0);
            order.setNum(cart.getNum());
            orderMapper.insertSelective(order);
            // 删除原有购物车中的物品
            cartMapper.deleteByPrimaryKey(cart.getId());
        }
    }

    @Override
    public List<Order> findAll(Integer uid) {
        OrderExample example = new OrderExample();
        OrderExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(0);
        criteria.andUidEqualTo(uid);
        List<Order> orderList = orderMapper.selectByExample(example);
        return orderList;
    }

    @Transactional
    public void sendGoods(List<Order> orders, Integer aid) {
        if(aid==null){
            throw  new RuntimeException("收货人不存在，请重试");
        }
        for (Order order : orders) {
            order.setRecid(aid);
            order.setStatus(2);
            orderMapper.updateByPrimaryKeySelective(order);
        }
    }
}
